import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/details/box_details_page.dart';
import 'package:nft_shop/box/page/details/split_box_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/main.dart';
import 'package:nft_shop/market/page/details/works_details_page.dart';
import 'package:nft_shop/my/conteroller/my_conteroller.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/order/my_resell_page.dart';
import 'package:nft_shop/my/page/set/check_work_page.dart';
import 'package:nft_shop/my/page/set/my_royalties_record_page.dart';
import 'package:nft_shop/my/page/write/my_works_creation_page.dart';
import 'package:nft_shop/my/view/album_hint.dart';
import 'package:nft_shop/my/view/my_check_work_widget.dart';
import 'package:nft_shop/my/view/my_editor_works_bottom.dart';
import 'package:nft_shop/my/view/my_new_album_widget.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/image_util.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/util/route_observer.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyListTypePage extends StatefulWidget {
  int? section;
  int? row;

  MyListTypePage({Key? key, this.section, this.row}) : super(key: key);

  @override
  _MyListTypePageState createState() => _MyListTypePageState();
}

class _MyListTypePageState extends State<MyListTypePage>
    with AutomaticKeepAliveClientMixin, RouteAware {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    try{
      _status = value;
      setState(() {});
    }catch(e){}
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    RouteUtils.routeObserver.unsubscribe(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    RouteUtils.routeObserver
        .subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  //回到当前页面
  @override
  void didPopNext() {
    print("我的界面--刷新数据---");
    refresh();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
    eventBus.on<String>().listen((it) {
      if (it == "mySelectType") {
        if (MyConteroller.to.rowIndex == widget.row &&
            MyConteroller.to.sectionIndex == widget.section) {
          print(
              "刷新了--------${MyConteroller.to.sectionIndex}--${MyConteroller.to.rowIndex}");
          refresh();
        }
      }
    });
  }

  //获取数据
  Future<List> loadData({int? pageNum}) async {
    print(
        "请求参数----${widget.section! == 3 ? 4 : widget.section!}--${widget.row!}");
    return await ServiceRepository.myGoodsSpecialList(
        page: pageNum!,
        pageSize: pageSize,
        smallType: widget.row!,
        bigType: widget.section! == 3 ? 4 : widget.section!);
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      print("数组个数--${data.length}");
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      status = LoadStatusType.empty;
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      header: WaterDropHeader(),
      footer: ClassicFooter(
        noDataText: "",
      ),
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: true,
      child: _gridViewWidget(),
    );
  }

  ///我的
  Widget _gridViewWidget() {
    if (status != LoadStatusType.success) {
      return StatusViews(status);
    }
    print("当前数组个数----${list.length}");
    return CustomScrollView(
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.all(8.0),
          sliver: SliverGrid(
            //Grid
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 15,
              mainAxisSpacing: 15,
              childAspectRatio: 167 / 230,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                MyGoodsSpecialModel model = list[index];
                return _itemWidget(model);
              },
              childCount: list.length,
            ),
          ),
        ),
        // SliverToBoxAdapter(
        //   child: Padding(
        //     padding: const EdgeInsets.only(top: 20),
        //     child: LoadAssetImage(
        //       "footer_img",
        //       height: 33,
        //     ),
        //   ),
        // )
      ],
    );
  }

  ///item
  Widget _itemWidget(MyGoodsSpecialModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    //index 0我的拥有 1我的卖出 2我的创作 3售卖中
    //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
    //special_cast_status铸造状态 1未铸造 2铸造中 3已铸造
    //goods_status状态: 0待上架 1正在出售 2被买家锁定 3买家已支付 4.超时 5已取消
    //special_sell_status 转售状态 1是0否
    String showType = "";
    if (widget.section == 1) {
      if (model.type == 4) {
        showType = "藏品";
      } else if (model.type == 5) {
        showType = "盲盒待拆";
      } else if (model.type == 6) {
        showType = "盲盒已拆";
      }
    } else if (widget.section == 2) {
      showType = "已卖出";
    } else if (widget.section == 3) {
      if (model.num == 0) {
        showType = "已售罄";
      } else {
        if (UserController.to.member.id == model.framerMemberId) {
          showType = "首发售卖中";
        } else {
          showType = "转售中";
        }
      }
    }
    return InkWell(
      onTap: () {
        if (widget.section == 2) {
          //我卖出的按类型type进行判断  类型 1藏品 2盲盒未拆 3盲盒已拆
          if (model.type == 2 || model.type == 3) {
            //1单个盲盒详情 2整体铸造详情  3整体详情
            Get.to(BoxDetailsPage(
                id: model.goodsId!, type: 1, isHidePayment: true));
          } else if (model.type == 1) {
            //1单个藏品详情 2整体铸造详情  3整体详情
            Get.to(WorksDetailsPage(
                id: model.goodsId!, type: 1, isHidePayment: true));
          }
        } else {
          //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
          print("点击了--${model.type}-----${model.toJson()}");
          if (model.type == 2 || model.type == 5 || model.type == 6) {
            int type;
            //1单个盲盒详情 2整体铸造详情  3整体详情
            if (model.type == 2) {
              type = 3;
            } else if (model.type == 5) {
              type = 1;
            } else {
              type = 1;
            }
            if (ObjectUtil.isEmpty(model.specialId)) {
              Get.to(BoxDetailsPage(
                  id: model.goodsId!, type: type, isHidePayment: true));
            }else {
              Get.to(BoxDetailsPage(
                  id: model.specialId!, type: type, isHidePayment: true));
            }
          } else if (model.type == 1 || model.type == 4) {
            int type;
            //1单个藏品详情 2整体铸造详情  3整体详情
            if (model.type == 1) {
              type = 3;
            } else {
              type = 1;
            }
            if (ObjectUtil.isEmpty(model.specialId)) {
              Get.to(WorksDetailsPage(
                  id: model.goodsId!, type: type, isHidePayment: true));
            } else {
              Get.to(WorksDetailsPage(
                  id: model.specialId!, type: type, isHidePayment: true));
            }
          }
        }
      },
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: LoadImage(
                    model.thumb ?? "",
                    width: double.infinity,
                    fit: BoxFit.fitHeight,
                    height: itemHeight,
                  ),
                ),
                Positioned(
                  left: 9,
                  top: 8,
                  child: _objectState(showType),
                ),
                Positioned(
                  bottom: 5,
                  left: 5,
                  child: _objectType(
                    model.specialTypeName ?? "",
                  ),
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          model.title ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontFamily: Global.mySemiboldFont,
                              fontSize: 14,
                              color: Global.kTheme.textPrimary4),
                        ),
                        SizedBox(
                          height: 2,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(9),
                              child: LoadImage(
                                model.portrait ?? "header_img",
                                width: 18,
                                height: 18,
                                holderImg: "header_img",
                              ),
                            ),
                            SizedBox(
                              width: 4,
                            ),
                            Expanded(
                              child: Text(
                                model.nickname ?? "",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 12,
                                    color: Global.kTheme.textPrimary0,
                                    fontFamily: Global.mySemiboldFont),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        "¥${model.price ?? ""}",
                        style: TextStyle(
                            fontFamily: Global.myDINFont,
                            color: widget.section == 2
                                ? Global.kTheme.textPrimary3
                                : Global.kTheme.textPrimary0,
                            fontSize: 16),
                      ),
                      SizedBox(
                        height: 2,
                      ),
                      Visibility(
                        visible: showType == "已卖出" || showType == "铸造中"
                            ? false
                            : true,
                        child: InkWell(
                          onTap: () {
                            botttomOperationView(model);
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 10, vertical: 2),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: Global.kTheme.colorBackground3),
                            child: Text(
                              "操作",
                              style: TextStyle(
                                  fontSize: 12,
                                  color: Global.kTheme.textPrimary5,
                                  fontFamily: Global.mySemiboldFont),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //item
  Widget _itemAlbumWidget(MyGoodsSpecialModel model) {
    double itemWidth = (Get.width - 45) / 2;
    double itemHeight = itemWidth * 173 / 167;
    return InkWell(
      onTap: () {},
      child: Container(
        decoration: BoxDecoration(
            color: Global.kTheme.colorBackground1,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                  color: Color(0x80E6E6E6),
                  offset: Offset(2.0, 2.0), //阴影xy轴偏移量
                  blurRadius: 8.0, //阴影模糊程度
                  spreadRadius: 3.0 //阴影扩散程度
                  )
            ]),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10), topRight: Radius.circular(10)),
              child: LoadImage(
                model.thumb ?? "",
                width: double.infinity,
                height: itemHeight,
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        model.title ?? "",
                        style: TextStyle(
                            fontFamily: Global.mySemiboldFont,
                            fontSize: 14,
                            color: Global.kTheme.textPrimary4),
                      ),
                      SizedBox(
                        height: 2,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            "版权金",
                            style: TextStyle(
                                fontSize: 12,
                                color: Global.kTheme.inputHint1,
                                fontFamily: Global.mySemiboldFont),
                          ),
                          SizedBox(
                            width: 2,
                          ),
                          Text(
                            model.specialAlbumRate ?? "",
                            style: TextStyle(
                                fontSize: 15,
                                color: Global.kTheme.textPrimary0,
                                fontFamily: Global.mySemiboldFont),
                          ),
                        ],
                      )
                    ],
                  ),
                  InkWell(
                    onTap: () {
                      print("点击了编辑----");
                      botttomOperationView(model);
                    },
                    child: Container(
                      padding:
                          EdgeInsets.symmetric(horizontal: 10, vertical: 1),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                          color: Global.kTheme.colorBackground3),
                      child: Text(
                        "编辑",
                        style: TextStyle(
                            fontSize: 12,
                            color: Global.kTheme.textPrimary5,
                            fontFamily: Global.mySemiboldFont),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  //弹出框
  void botttomOperationView(MyGoodsSpecialModel model) {
    //index 0我的拥有 1我的卖出 2我的创作 3售卖中
    //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
    //special_cast_status铸造状态 1未铸造 2铸造中 3已铸造
    //goods_status状态: 0待上架 1正在出售 2被买家锁定 3买家已支付 4.超时 5已取消
    //special_sell_status 转售状态 1是0否
    List<String> lisName = [];
    if (widget.section == 1) {
      if (model.type == 4) {
        lisName.add("上架转售");
        lisName.add("查看画作");
        lisName.add("保存图片");
      } else if (model.type == 5) {
        lisName.add("拆盲盒");
        lisName.add("上架转售");
        lisName.add("查看画作");
        lisName.add("保存图片");
      } else if (model.type == 6) {
        lisName.add("上架转售");
        lisName.add("查看画作");
        lisName.add("保存图片");
      }
    } else if (widget.section == 3) {
      if (model.num != 0) {
        lisName.add("下架转售");
      }

      lisName.add("查看画作");
      lisName.add("保存图片");
    }

    if (lisName.length == 0) return;
    showModalBottomSheet<void>(
        context: context,

        /// 禁止拖动关闭
        enableDrag: false,

        /// 使用true则高度不受16分之9的最高限制
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (_) {
          return MyEditorWorksBottom(
            listName: lisName,
            onTap: (index) async {
              if (lisName[index] == "拆盲盒") {
                print("goodid是--${model.goodsId}-${model.specialId}");
                Get.to(SplitBoxPage(
                  goodid: model.goodsId ?? "",
                  id: model.goodsId ?? "",
                  isSingle: true,
                ));
              } else if (lisName[index] == "上架转售") {
                try {
                  EasyLoading.show(status: "加载中");
                  MemberExtendModel extend =
                      await ServiceRepository.memberExtend();
                  EasyLoading.dismiss();
                  if (ObjectUtil.isEmpty(extend.alipayAccount)) {
                    print("执行操作");
                    Utils.showElasticDialog<void>(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) {
                        return CollectionDialog();
                      },
                    );
                  } else {
                    Get.to(MyResellPage(
                      model: model,
                    ));
                  }
                } catch (e, s) {}
              } else if (lisName[index] == "发布售卖") {
                try {
                  EasyLoading.show(status: "加载中");
                  MemberExtendModel extend =
                      await ServiceRepository.memberExtend();
                  EasyLoading.dismiss();
                  if (extend.alipayAccount!.length == 0) {
                    Utils.showElasticDialog<void>(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) {
                        return CollectionDialog();
                      },
                    );
                  } else {
                    Get.to(MyResellPage(
                      model: model,
                    ));
                  }
                } catch (e, s) {}
              } else if (lisName[index] == "查看画作") {
                Utils.showElasticDialog<void>(
                  context: context,
                  builder: (BuildContext context) {
                    return MyCheckWorkWidget(model.thumb!);
                  },
                );
              } else if (lisName[index] == "编辑作品") {
                //type类型 类型 1整体藏品
                Get.to(MyWorksCreationPage(
                  model: model,
                ));
              } else if (lisName[index] == "保存图片") {
                print("图片地址---${model.thumb!}");
                AppUtil.saveImage(model.thumb!);
              } else if (lisName[index] == "编辑专辑") {
                showModalBottomSheet<void>(
                    context: context,
                    backgroundColor: Colors.transparent,

                    /// 禁止拖动关闭
                    enableDrag: false,

                    /// 使用true则高度不受16分之9的最高限制
                    isScrollControlled: true,
                    builder: (_) => MyNewAlbumWidget(
                          album: AlbumListModel.fromJsonToGoods(model.toJson()),
                          onPressed: () {
                            refresh();
                          },
                        ));
              } else if (lisName[index] == "版税记录") {
                Get.to(MyRoyaltiesRecordPage(
                  id: model.specialAlbumId ?? "",
                ));
              } else if (lisName[index] == "查看作品") {
                Get.to(CheckWorkPage(
                  id: model.specialAlbumId ?? "",
                ));
              } else if (lisName[index] == "立即铸造") {
                //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
                if (model.type == 1) {
                  Get.to(WorksDetailsPage(id: model.specialId ?? "", type: 2));
                } else {
                  Get.to(BoxDetailsPage(id: model.specialId ?? "", type: 2));
                }
              } else if (lisName[index] == "下架转售") {
                EasyLoading.show(status: "加载中");
                try {
                  //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
                  if (model.type == 4 || model.type == 5 || model.type == 6) {
                    //单个盲盒/藏品下架
                    await ServiceRepository.goodsSoldOut(id: model.goodsId);
                  } else if (model.type == 1 || model.type == 2) {
                    await ServiceRepository.soldOut(id: model.specialId);
                  }
                  EasyLoading.showToast("下架成功");
                  refresh();
                } catch (e, s) {
                  EasyLoading.showToast(http.setError(e, s));
                }
              }
            },
          );
        });
  }

  ///藏品状态
  Widget _objectState(String state) {
    Color color = Color(0xFF50E3C2);
    return Container(
        height: 24,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: Global.kTheme.colorBackground3.withAlpha(100),
        ),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        child: Text(
          state,
          style: TextStyle(
              color: Global.kTheme.textPrimary5,
              fontSize: 12,
              fontFamily: Global.mySemiboldFont),
        ));
  }

  ///藏品类型
  Widget _objectType(String state) {
    return Container(
      height: 17,
      decoration: BoxDecoration(
        color: Global.kTheme.colorBackground3,
      ),
      padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Text(
        state,
        style: TextStyle(
            color: Global.kTheme.textPrimary5,
            fontSize: 10,
            fontFamily: Global.mySemiboldFont),
      ),
    );
  }
}
